package conson.tech.manage.common.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ClassName: OssUploadUtils
 * Description:
 * Author: HXL
 * Date: 2020/4/23 5:22 下午
 * Version: 1.0
 */
@Slf4j
public class OssUploadUtils {
    private String bucket;
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;

    public OssUploadUtils(String bucket, String endpoint, String accessKeyId, String accessKeySecret) {
        this.bucket = bucket;
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
    }

    public OSSClient initOssClient() {
        log.info("开始连接OSS存储服务器域名：" + this.endpoint + "，accessKeyId:" + this.accessKeyId + "，accessKeySecret:" + this.accessKeySecret);
        return new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
    }

    public String upload(String path, InputStream inputStream, String contentType, Long length) {
        log.info("OSS上传文件开始...");
        int year = Calendar.getInstance().get(1);
        int month = Calendar.getInstance().get(2) + 1;
        int day = Calendar.getInstance().get(5);
        String dir = "/" + year + "/" + month + "/" + day + "/";
        path = path + dir;
        String remoteName = UUID.randomUUID().toString() + contentType;
        boolean isFinish = false;

        try {
            try {
                OSSClient oSSClient;
                ObjectMetadata meta;
                try {
                    oSSClient = this.initOssClient();
                } catch (Exception var27) {
                    log.error("连接OSS云存储服务器失败：" + var27);
                    meta = null;
                    return null;
                }
                String bucketName = this.bucket;
                bucketName = this.isNotBucketName(bucketName, oSSClient);
                if (!StringUtils.isEmpty(bucketName)) {
                    this.changeMakeWorkingDir(path, bucketName, oSSClient);
                    meta = new ObjectMetadata();
                    meta.setContentLength(length);
                    String fileName = new String(remoteName.getBytes("GBK"), "iso-8859-1");
                    path = path.substring(1, path.length());
                    String objectName = path + fileName;
                    PutObjectResult result = oSSClient.putObject(bucketName, objectName, inputStream, meta);
                    if (result != null) {
                        isFinish = true;
                        log.info("OSS云存储服务器文件上传成功!");
                    }

                    return dir + remoteName;
                }
            } catch (Exception var28) {
                log.error("往OSS云存储服务器上传文件失败：" + var28);
            }

            return dir + remoteName;
        } finally {
            try {
                if (isFinish) {
                    inputStream.close();
                }
            } catch (IOException var26) {
                log.error("关闭文件流出错", var26);
            }

        }
    }
    public String upload(String path, String remoteName,InputStream inputStream,  Long length) {
        log.info("OSS上传文件开始...");
        int year = Calendar.getInstance().get(1);
        int month = Calendar.getInstance().get(2) + 1;
        int day = Calendar.getInstance().get(5);
        String dir = "/" + year + "/" + month + "/" + day + "/";
        path = path + dir;
        boolean isFinish = false;

        try {
            try {
                OSSClient oSSClient;
                ObjectMetadata meta;
                try {
                    oSSClient = this.initOssClient();
                } catch (Exception var27) {
                    log.error("连接OSS云存储服务器失败：" + var27);
                    meta = null;
                    return null;
                }
                String bucketName = this.bucket;
                bucketName = this.isNotBucketName(bucketName, oSSClient);
                if (!StringUtils.isEmpty(bucketName)) {
                    this.changeMakeWorkingDir(path, bucketName, oSSClient);
                    meta = new ObjectMetadata();
                    meta.setContentLength(length);
                    String fileName = new String(remoteName.getBytes("GBK"), "iso-8859-1");
                    path = path.substring(1, path.length());
                    String objectName = path + fileName;
                    PutObjectResult result = oSSClient.putObject(bucketName, objectName, inputStream, meta);
                    if (result != null) {
                        isFinish = true;
                        log.info("OSS云存储服务器文件上传成功!");
                    }

                    return dir + remoteName;
                }
            } catch (Exception var28) {
                log.error("往OSS云存储服务器上传文件失败：" + var28);
            }

            return dir + remoteName;
        } finally {
            try {
                if (isFinish) {
                    inputStream.close();
                }
            } catch (IOException var26) {
                log.error("关闭文件流出错", var26);
            }

        }
    }
    public String isNotBucketName(String bucketName, OSSClient oSSClient) {
        boolean exists = oSSClient.doesBucketExist(bucketName);
        if (!exists) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String nowTime = "";

            try {
                nowTime = sdf.format(new Date());
            } catch (Exception var8) {
                var8.printStackTrace();
            }

            bucketName = nowTime + "bucketname";

            try {
                oSSClient.createBucket(bucketName);
                log.info("自动创建bucketName:" + bucketName + "成功！");
            } catch (OSSException var7) {
                log.error("自动创建bucketName:" + bucketName + "失败，请手动创建！");
                return null;
            }
        }

        return bucketName;
    }

    private void changeMakeWorkingDir(String path, String bucketName, OSSClient oSSClient) throws IOException {
        path = path.substring(1, path.length());
        boolean exists = oSSClient.doesObjectExist(bucketName, path);
        if (!exists) {
            path = new String(path.getBytes("GBK"), "iso-8859-1");
            if (!StringUtils.isEmpty(path)) {
                ObjectMetadata objectMeta = new ObjectMetadata();
                byte[] buffer = new byte[0];
                ByteArrayInputStream in = new ByteArrayInputStream(buffer);
                objectMeta.setContentLength(0L);

                try {
                    oSSClient.putObject(bucketName, path, in, objectMeta);
                } catch (Exception var12) {
                    log.error("创建文件夹:" + path + "失败！");
                } finally {
                    in.close();
                }
            }
        }

    }

    public boolean deleteObjectFiles(List<String> filePathList) {

        log.info("OSS删除文件开始...");
        DeleteObjectsRequest objectRequests = new DeleteObjectsRequest(this.bucket);

        try {
            OSSClient oSSClient = null;

            try {
                oSSClient = this.initOssClient();
            } catch (Exception var10) {
                log.error("连接OSS云存储服务器失败：" + var10);
            }

            String bucketName = this.bucket;
            if (!StringUtils.isEmpty(bucketName)) {
                objectRequests.setBucketName(bucketName);
                objectRequests.setKeys(filePathList);
                oSSClient.deleteObjects(objectRequests);
            }
            return true;
        } catch (Exception var11) {
            log.error("OSS内部云服务器删除文件失败：" + var11);
        }
        log.info("OSS删除文件结束！.");
        return false;
    }

    public List<byte[]> getObjectFiles(List<String> filePathList) {

        log.info("OSS获取文件byte数组开始...");
        List<byte[]> listByte = new ArrayList();
        OSSClient oSSClient = null;

        try {
            try {
                oSSClient = this.initOssClient();
            } catch (Exception var19) {
               log.error("连接OSS云存储服务器失败：" + var19);

            }

            String bucketName = this.bucket;
            if (!StringUtils.isEmpty(bucketName)) {
                Iterator var6 = filePathList.iterator();

                while(var6.hasNext()) {
                    String strs = (String)var6.next();
                    GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, strs);
                    OSSObject ossObject = oSSClient.getObject(getObjectRequest);
                    InputStream in = ossObject.getObjectContent();
                    ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                    byte[] buff = new byte[100];
                    boolean var13 = false;

                    int rc;
                    while((rc = in.read(buff, 0, 100)) > 0) {
                        swapStream.write(buff, 0, rc);
                    }

                    byte[] bytes = swapStream.toByteArray();
                    listByte.add(bytes);
                }
            }
        } catch (Exception var20) {
            log.error("OSS内部云服务器获取文件byte数组失败：" + var20);
        }
        return listByte;
    }

}
